
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>通过一个问题学习map,filter,reduce语法 - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,比如一个从1-10的简单的数组，需要从中取奇数，你会怎么做？这个问题不难，有的少侠可能会使用for循环来过滤出偶数，某些少侠可能会使用while循环，又或是使用数组自带的filter方法。
这里，我,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">通过一个问题学习map,filter,reduce语法</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="/categories/Js"><b>「
                    </b>JS<b> 」</b></a>
                
                July 24, 2019
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2019/07/24/Js/%E9%80%9A%E8%BF%87%E4%B8%80%E4%B8%AA%E9%97%AE%E9%A2%98%E5%AD%A6%E4%B9%A0map-filter-reduce%E8%AF%AD%E6%B3%95/" title="通过一个问题学习map,filter,reduce语法" class="">通过一个问题学习map,filter,reduce语法</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    27k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    25 mins.
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/Js/" rel="tag">Js</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <h2 id="比如一个从1-10的简单的数组，需要从中取奇数，你会怎么做？"><a href="#比如一个从1-10的简单的数组，需要从中取奇数，你会怎么做？" class="headerlink" title="比如一个从1-10的简单的数组，需要从中取奇数，你会怎么做？"></a>比如一个从1-10的简单的数组，需要从中取奇数，你会怎么做？</h2><p>这个问题不难，有的少侠可能会使用for循环来过滤出偶数，某些少侠可能会使用while循环，又或是使用数组自带的filter方法。</p>
<p>这里，我们先不考虑使用for和while这些迭代方法，我们选择使用数组自带的filter方法，如果使用filter方法的话，</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"><span class="comment">// 过滤出所有奇数</span></span><br><span class="line">nums.filter(<span class="function"><span class="params">num</span> =&gt;</span> num % <span class="number">2</span> !== <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(nums);</span><br></pre></td></tr></table></figure>
<p>还是挺简单的对吧？</p>
<p>相信大部分少侠都能很轻松完成。</p>
<p>在filter函数内部，我们使用 <code>num % 2 !== 0</code> 来判断 是否是一个奇数，如果是一个奇数，就过滤出来。</p>
<p>在这里，有的少侠可能就会想到，如果把这个判断过程单独分成一个函数，会方便一些，也方便以后的修改扩展。</p>
<p>比如单独写一个isOdd函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> isOdd = <span class="function"><span class="params">num</span> =&gt;</span> num % <span class="number">2</span> !== <span class="number">0</span>;</span><br></pre></td></tr></table></figure>
<p>然后在filter里面使用这个函数，是吧？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> isOdd = <span class="function"><span class="params">num</span> =&gt;</span> num % <span class="number">2</span> !== <span class="number">0</span>;</span><br><span class="line"><span class="comment">// 过滤出所有奇数</span></span><br><span class="line"><span class="keyword">const</span> odd = nums.filter(isOdd);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(odd);</span><br></pre></td></tr></table></figure>
<h2 id="如果要把nums里面的数字翻倍，用map函数，又该怎么做呢？"><a href="#如果要把nums里面的数字翻倍，用map函数，又该怎么做呢？" class="headerlink" title="如果要把nums里面的数字翻倍，用map函数，又该怎么做呢？"></a>如果要把nums里面的数字翻倍，用map函数，又该怎么做呢？</h2><p>聪明的少侠这次肯定一下就明白了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"><span class="keyword">const</span> double = <span class="function"><span class="params">num</span> =&gt;</span> num *<span class="number">2</span>;</span><br><span class="line"><span class="keyword">const</span> doubleNumbers = nums.map(double);</span><br><span class="line"><span class="built_in">console</span>.log(doubleNumbers);</span><br></pre></td></tr></table></figure>
<h2 id="从nums里面过滤出所有奇数，并翻倍这些奇数。"><a href="#从nums里面过滤出所有奇数，并翻倍这些奇数。" class="headerlink" title="从nums里面过滤出所有奇数，并翻倍这些奇数。"></a>从nums里面过滤出所有奇数，并翻倍这些奇数。</h2><p>这个问题也不难是吧？</p>
<p>让我猜一下，一些少侠应该会写成下面这样：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> isOdd = <span class="function"><span class="params">num</span> =&gt;</span> num % <span class="number">2</span> !== <span class="number">0</span>;</span><br><span class="line"><span class="keyword">const</span> double = <span class="function"><span class="params">num</span> =&gt;</span> num *<span class="number">2</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> doubleNums = nums.filter(isOdd).map(double);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(doubleNums);</span><br></pre></td></tr></table></figure>
<h2 id="如果我们还想继续算出所有奇数翻倍后的和的话"><a href="#如果我们还想继续算出所有奇数翻倍后的和的话" class="headerlink" title="如果我们还想继续算出所有奇数翻倍后的和的话"></a>如果我们还想继续算出所有奇数翻倍后的和的话</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> isOdd = <span class="function"><span class="params">num</span> =&gt;</span> num % <span class="number">2</span> !== <span class="number">0</span>;</span><br><span class="line"><span class="keyword">const</span> double = <span class="function"><span class="params">num</span> =&gt;</span> num *<span class="number">2</span>;</span><br><span class="line"><span class="keyword">const</span> add = <span class="function">(<span class="params">sum,num</span>) =&gt;</span> sum += num;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> doubleNums = nums.filter(isOdd).map(double).reduce(add,<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(doubleNums);</span><br></pre></td></tr></table></figure>
<p>嗯，一个串一个看起来很酷是吧？ 最后的结果也是正确的。</p>
<p>这样串起来的后果就是，我们会遍历3次数组，filter的时候遍历一次，map的时候遍历一次，reduce的时候再遍历一次。</p>
<p>现在数组只有10个数字，影响还不大，但是如果是很大的数组，比如100万个数字，遍历3遍的话，那么就会多访问<strong>150万次</strong>，</p>
<p>想象一下，如果让你自己从中间取出所有奇数，翻倍，并求和，你会觉得怎么做简单一些呢？</p>
<blockquote>
<p>是不是觉得下面这样才比较正常？</p>
</blockquote>
<ul>
<li>首先，从第一个数字开始，如果它是奇数，就拿出来，翻倍，然后找个地方放起来</li>
<li>接着，继续看第二个数字，如果是偶数，就跳过，如果是奇数，就拿出来，翻倍，然后和开始的翻倍后的奇数加起来，找个地方放起来。</li>
<li>接着看第三个数字，以此类推，只要是奇数，就翻倍，然后和之前的结果加起来。</li>
<li>直到我们找寻到最后一个数字，就可以算出最终结果了，</li>
</ul>
<p>如果使用迭代的话，就是下面这样:<br><a id="more"></a></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> isOdd = <span class="function"><span class="params">num</span> =&gt;</span> num % <span class="number">2</span> !== <span class="number">0</span>;</span><br><span class="line"><span class="keyword">const</span> double = <span class="function"><span class="params">num</span> =&gt;</span> num *<span class="number">2</span>;</span><br><span class="line"><span class="keyword">const</span> add = <span class="function">(<span class="params">sum,num</span>) =&gt;</span> sum += num;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 保存最终结果</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> result = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i =<span class="number">0</span>; i&lt; nums.length; i++)&#123;</span><br><span class="line">    <span class="keyword">if</span>(nums[i]%<span class="number">2</span> != <span class="number">0</span>)&#123;</span><br><span class="line">        result = result + nums[i]*<span class="number">2</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(result); <span class="comment">// 50</span></span><br></pre></td></tr></table></figure>
<p>没错，通常这样才是正常的操作。</p>
<p>但是，</p>
<p>这样的代码不太方便，</p>
<p>少侠你肯定也不想每次都写这么一大堆for循环语句吧？</p>
<p>所以，我们可以先试着继续优化一下。</p>
<p>我们首先试着用一个叫做magic(魔法)的函数把这些步骤包裹起来:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> magic = <span class="function"><span class="params">array</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> length = array.length,</span><br><span class="line">    <span class="keyword">let</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">let</span> sum = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(i, i &lt; length; i++)&#123;</span><br><span class="line">        <span class="keyword">if</span>(array[i] % <span class="number">2</span> !== <span class="number">0</span>)&#123;</span><br><span class="line">            sum = sum + array[i]*<span class="number">2</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sum;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(magic(nums)); <span class="comment">// 50</span></span><br></pre></td></tr></table></figure>
<p>现在看起来好多了，不过，magic内部的操作看起来不是很清晰，</p>
<p>其他少侠看见了可能很难一眼就明白magic函数在做什么,</p>
<p>我们可以试着把里面的一些步骤分成更小的函数:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> isOdd = <span class="function"><span class="params">num</span> =&gt;</span> num % <span class="number">2</span> !== <span class="number">0</span>;</span><br><span class="line"><span class="keyword">const</span> double = <span class="function"><span class="params">num</span> =&gt;</span> num *<span class="number">2</span>;</span><br><span class="line"><span class="keyword">const</span> add = <span class="function">(<span class="params">sum,num</span>) =&gt;</span> sum += num;</span><br><span class="line"><span class="keyword">const</span> magic = <span class="function"><span class="params">array</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> length = array.length,</span><br><span class="line">    <span class="keyword">let</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">let</span> sum = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(i, i &lt; length; i++)&#123;</span><br><span class="line">        <span class="keyword">if</span>(isOdd(array[i]))&#123;</span><br><span class="line">            sum = add(sum,double(array[i]));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sum;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(magic(nums)); <span class="comment">// 50</span></span><br></pre></td></tr></table></figure>
<p>现在比较简洁也比较清晰了，不过，假如我们现在要计算是偶数而不是奇数怎么办呢？</p>
<p>或者如果更复杂些，如果是偶数，就反过来，除以二，然后求和，又该怎么办呢？</p>
<p>难道我们又要复制一次magic函数，然后改动for循环里面的逻辑吗？</p>
<p>也许，我们可以把for循环内部的逻辑单独提取成一个外部函数！</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> isOdd = <span class="function"><span class="params">num</span> =&gt;</span> num % <span class="number">2</span> !== <span class="number">0</span>;</span><br><span class="line"><span class="keyword">const</span> isEvent = <span class="function"><span class="params">num</span> =&gt;</span> !isOdd(num)</span><br><span class="line"><span class="keyword">const</span> double = <span class="function"><span class="params">num</span> =&gt;</span> num *<span class="number">2</span>;</span><br><span class="line"><span class="keyword">const</span> part = <span class="function"><span class="params">num</span> =&gt;</span> num /<span class="number">2</span>;</span><br><span class="line"><span class="keyword">const</span> add = <span class="function">(<span class="params">sum,num</span>) =&gt;</span> sum += num;</span><br><span class="line"><span class="keyword">const</span> magic = <span class="function">(<span class="params">array,fn,sum</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> length = array.length,</span><br><span class="line">    <span class="keyword">let</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(i, i &lt; length; i++)&#123;</span><br><span class="line">        sum = magicFriends(sum,array[i])</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sum;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">magicFriends</span>(<span class="params">sum,num</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(isOdd(num))&#123;</span><br><span class="line">        sum = add(sum,double(num));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sum ;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(magic(nums,magicFriends,<span class="number">0</span>)); <span class="comment">// 50</span></span><br></pre></td></tr></table></figure>
<h2 id="接下来就是见证奇迹的时刻！"><a href="#接下来就是见证奇迹的时刻！" class="headerlink" title="接下来就是见证奇迹的时刻！"></a>接下来就是见证奇迹的时刻！</h2><p>首先，我们给代码里面部分函数和参数改一下名字:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> isOdd = <span class="function"><span class="params">num</span> =&gt;</span> num % <span class="number">2</span> !== <span class="number">0</span>;</span><br><span class="line"><span class="keyword">const</span> isEvent = <span class="function"><span class="params">num</span> =&gt;</span> !isOdd(num)</span><br><span class="line"><span class="keyword">const</span> double = <span class="function"><span class="params">num</span> =&gt;</span> num *<span class="number">2</span>;</span><br><span class="line"><span class="keyword">const</span> part = <span class="function"><span class="params">num</span> =&gt;</span> num /<span class="number">2</span>;</span><br><span class="line"><span class="keyword">const</span> add = <span class="function">(<span class="params">sum,num</span>) =&gt;</span> sum += num;</span><br><span class="line"><span class="keyword">const</span> reduce = <span class="function">(<span class="params">array,reducer,result</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> length = array.length,</span><br><span class="line">    <span class="keyword">let</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(i, i &lt; length; i++)&#123;</span><br><span class="line">        result = reducer(sum,array[i])</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">consot magicFriends = <span class="function">(<span class="params">sum,num</span>) =&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(isOdd(num))&#123;</span><br><span class="line">        sum = add(sum,double(num));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sum ;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(reduce(nums,magicFriends,<span class="number">0</span>)); <span class="comment">// 50</span></span><br></pre></td></tr></table></figure>
<p>是不是有点眼熟了？ 接着，我们换成数组自带的reduce函数:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> isOdd = <span class="function"><span class="params">num</span> =&gt;</span> num % <span class="number">2</span> !== <span class="number">0</span>;</span><br><span class="line"><span class="keyword">const</span> isEvent = <span class="function"><span class="params">num</span> =&gt;</span> !isOdd(num)</span><br><span class="line"><span class="keyword">const</span> double = <span class="function"><span class="params">num</span> =&gt;</span> num *<span class="number">2</span>;</span><br><span class="line"><span class="keyword">const</span> part = <span class="function"><span class="params">num</span> =&gt;</span> num /<span class="number">2</span>;</span><br><span class="line"><span class="keyword">const</span> add = <span class="function">(<span class="params">sum,num</span>) =&gt;</span> sum += num;</span><br><span class="line">consot magicFriends = <span class="function">(<span class="params">sum,num</span>) =&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(isOdd(num))&#123;</span><br><span class="line">        sum = add(sum,double(num));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sum ;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(nums.reduce(magicFriends,<span class="number">0</span>)); <span class="comment">// 50</span></span><br></pre></td></tr></table></figure>
<h2 id="最后回到我们上面的问题"><a href="#最后回到我们上面的问题" class="headerlink" title="最后回到我们上面的问题:"></a>最后回到我们上面的问题:</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>,<span class="number">10</span>];</span><br><span class="line"><span class="keyword">const</span> isOdd = <span class="function"><span class="params">num</span> =&gt;</span> num % <span class="number">2</span> !== <span class="number">0</span>;</span><br><span class="line"><span class="keyword">const</span> double = <span class="function"><span class="params">num</span> =&gt;</span> num *<span class="number">2</span>;</span><br><span class="line"><span class="keyword">const</span> add = <span class="function">(<span class="params">sum,num</span>) =&gt;</span> sum += num;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> result = nums.reduces(<span class="function">(<span class="params">sum,num</span>)=&gt;</span> isOdd(num) ? add(sum,dobule(num) : sum,<span class="number">0</span>));</span><br><span class="line"><span class="built_in">console</span>.log(result); <span class="comment">// 50</span></span><br></pre></td></tr></table></figure>
<p>这次我们用reduce只遍历了一次数组就完成了之前的操作！</p>
<p>现在知道为什么之前要把reduce叫做magic(魔法)了吧！</p>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#比如一个从1-10的简单的数组，需要从中取奇数，你会怎么做？"><span class="toc-number">1.</span> <span class="toc-text">比如一个从1-10的简单的数组，需要从中取奇数，你会怎么做？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#如果要把nums里面的数字翻倍，用map函数，又该怎么做呢？"><span class="toc-number">2.</span> <span class="toc-text">如果要把nums里面的数字翻倍，用map函数，又该怎么做呢？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#从nums里面过滤出所有奇数，并翻倍这些奇数。"><span class="toc-number">3.</span> <span class="toc-text">从nums里面过滤出所有奇数，并翻倍这些奇数。</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#如果我们还想继续算出所有奇数翻倍后的和的话"><span class="toc-number">4.</span> <span class="toc-text">如果我们还想继续算出所有奇数翻倍后的和的话</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#接下来就是见证奇迹的时刻！"><span class="toc-number">5.</span> <span class="toc-text">接下来就是见证奇迹的时刻！</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#最后回到我们上面的问题"><span class="toc-number">6.</span> <span class="toc-text">最后回到我们上面的问题:</span></a></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
